package com.robusta.cityuate.dialogs;

import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.widget.DatePicker;
import android.widget.EditText;

import com.robusta.cityuate.utils.TimeUtils;

public class DatePickerFragment extends DialogFragment implements
		DatePickerDialog.OnDateSetListener {
	public static final String DATE_PICKER_TAG = "datePicker";

	private static final String FIELD_ID = "fieldID";

	private static final String MIN_DATE = "minDate";

	private static final String MAX_DATE = "maxDate";
	
	EditText dateView;
	int dateViewId;
	
	Calendar minDate;
	Calendar maxDate;

	
	public static DatePickerFragment getInstance(int viewId,
			Calendar minDate, Calendar maxDate) {
		DatePickerFragment f = new DatePickerFragment();
//		f.dateViewId = i;
//		f.minDate = minDate;
//		f.maxDate = maxDate;
		
		Bundle info=new Bundle();
		info.putInt(FIELD_ID, viewId);
		info.putSerializable(FIELD_ID, viewId);
		info.putSerializable(MIN_DATE, minDate);
		info.putSerializable(MAX_DATE, maxDate);
		f.setArguments(info);
		return f;
	}
@Override
public void onCreate(Bundle savedInstanceState) {
	
	super.onCreate(savedInstanceState);
	dateViewId=getArguments().getInt(FIELD_ID);
	minDate=(Calendar)getArguments().getSerializable(MIN_DATE);
	maxDate=(Calendar)getArguments().getSerializable(MAX_DATE);
	
}
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		// Use the current date as the default date in the picker
		Calendar c = Calendar.getInstance();
		System.out.println("field is null "+dateView!=null);
		dateView=(EditText)getActivity().findViewById(dateViewId);
		if (dateView!=null&&dateView.getText().length() != 0)
			c = TimeUtils.getCalendarFromFormat(dateView.getText().toString(),
					TimeUtils.DATE_FORMAT);

		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);
		// Create a new instance of DatePickerDialog and return it
	
		LimitedRangeDatePickerDialog pickerDialog = new LimitedRangeDatePickerDialog(
				getActivity(), this, year, month, day, minDate, maxDate);
		
		
		return pickerDialog;
	}

	public void onDateSet(DatePicker view, int year, int month, int day) {
		Time chosenDate = new Time();
		chosenDate.set(day, month, year);
		long dtDob = chosenDate.toMillis(true);
		CharSequence strDate = DateFormat.format(
				TimeUtils.DATE_FORMAT.subSequence(0, TimeUtils.DATE_FORMAT.length()), dtDob);
		dateView=(EditText)getActivity().findViewById(dateViewId);
		dateView.setText(strDate);

	}

	
}